import frappe

def create_quality_inspections(doc, method):
    '''创建采购入库后自动创建质检单'''

    # 判断是不是退货单，退货单不创建质检单
    if doc.is_return:
        return  # 是退货单，直接跳过

    for item in doc.items:
        # 如果该物料启用了质检（可选检查项）
        if not item.item_code:
            continue

        item_details = frappe.get_doc("Item", item.item_code)
        if not item_details.inspection_required_before_purchase:
            continue  # 如果该物料未启用采购质检，不创建

        qi = frappe.new_doc("Quality Inspection")
        qi.inspection_type = "Incoming"
        qi.reference_type = "Purchase Receipt"
        qi.reference_name = doc.name
        qi.item_code = item.item_code
        # 样本大小默认给0.1
        qi.sample_size = 0.1
        qi.batch_no = item.batch_no or ""
        qi.stock_uom = item.uom
        qi.inspected_by = frappe.session.user
        qi.report_date = frappe.utils.nowdate()
        qi.supplier = doc.supplier
        # 检验结果
        # qi.append("readings", {
        #     "specification": "Auto-generated",
        #     "reading_value": item.qty,
        # })

        qi.save(ignore_permissions=True)
        frappe.msgprint(f"自动创建质检单：{qi.name}")